package com.hancheng.commoncloud.framework.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import feign.codec.Decoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * feign远程调用日期格式
 */
@Configuration
public class FeignJacksonConfig {

    private static class MultiFormatDateDeserializer extends JsonDeserializer<Date> {

        private static final List<SimpleDateFormat> formats = Arrays.asList(
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
                new SimpleDateFormat("yyyy-MM-dd")
        );

        @Override
        public Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
            String dateStr = p.getText().trim();
            for (SimpleDateFormat format : formats) {
                try {
                    return format.parse(dateStr);
                } catch (ParseException ignored) {
                }
            }
            throw new IOException("Cannot parse date: " + dateStr);
        }
    }

    @Bean
    public ObjectMapper feignObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        // 不要忽略未知字段，按需配置
        mapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        // 注册多格式日期反序列化器
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Date.class, new MultiFormatDateDeserializer());
        mapper.registerModule(module);

        return mapper;
    }

    @Bean
    public Decoder feignDecoder(ObjectMapper feignObjectMapper) {
        HttpMessageConverter<?> converter = new MappingJackson2HttpMessageConverter(feignObjectMapper);
        ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(converter);
        return new SpringDecoder(objectFactory);
    }
}
